<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
		<meta content="yes" name="apple-mobile-web-app-capable" />
		<meta content="black" name="apple-mobile-web-app-status-bar-style" />
		<meta content="telephone=no" name="format-detection" />
		<meta content="email=no" name="format-detection" />
		<title>终端设置</title>
		<link rel="stylesheet" href="../../css/s_plus.css" />
		<link rel="stylesheet" href="../../css/base.css?s=20181206" />
		<link rel="stylesheet" href="../../css/layout.css" />
		<link rel="stylesheet" href="../../css/choice.css" />
		<link rel="stylesheet" href="../../css/hui.css" />
		<!--<link rel="stylesheet" href="../../css/mui.min.css" />-->

		<script type="text/javascript" src="../../libs/vue.js"></script>
		<script type="text/javascript" src="../../js/jquery.1.9.1.min.js"></script>
		<script type="text/javascript" src="../../js/app/url.js"></script>
		<script type="text/javascript" src="../../js/mui.min.js"></script>
		<script type="text/javascript" src="../../js/app/ble.js"></script>

		<script type="text/javascript" src="../../libs/hui.js"></script>
		<script type="text/javascript" src="../../js/app/api.js?time=2019011021"></script>
		<script type="text/javascript" src="../../js/control/pop.js"></script>
		<script type="text/javascript" src="../../js/md5.js"></script>
		<script type="text/javascript" src="../../js/control/select/iosSelect.js"></script>
		<link rel="stylesheet" href="../../js/control/select/iosSelect.css" />
	</head>

	<body>
		<div id="wrapper">

			<header class="f_l maxbox subhead">
				<a class="back" @click="back"><i class="iconfont">&#xe605;</i></a>
				<h1>终端设置</h1>
				<a class="f_r arrow_r" @click="refresh"><i class="iconfont">&#xe61a;</i></a>

			</header>
			<section class="f_l maxbox edit_list">

				<ul>
					<h3>终端信息</h3>

					<li>
						<b>终端ID</b>
						<p>{{Tid}}</p>
					</li>
					<li>
						<b>当前固件版本</b>
						<p>{{version}}</p>
					</li>

					<li>
						<b>NB信号值/卡号</b>
						<p>{{nb.xinhao}} / {{nb.card}}
							<!--<a id="nbBtn" @click="getNB">获取</a>-->
						</p>
					</li>

					<li>
						<b>电池电压值</b>
						<div>
							<p>{{status.dy}}</p>
						</div>
					</li>
					<li>
						<b>井盖是否破损</b>
						<div>
							<p>{{status.jgwps}}</p>
						</div>
					</li>
					<li>
						<b>底部是否开启</b>
						<div>
							<p>{{status.db}}</p>
						</div>
					</li>
					<li>
						<b>中部是否开启</b>
						<div>
							<p>{{status.zb}}</p>
						</div>
					</li>
					<li>
						<b>顶部是否开启</b>
						<div>
							<p>{{status.dingbu}}</p>
						</div>
					</li>

					<li>
						<b>压力值</b>
						<div>
							<p>{{status.ylz}}</p>
						</div>
					</li>
					<li>
						<b>水深</b>
						<div>
							<p>{{status.ss}}</p>
						</div>
					</li>
					<li>
						<b>燃气浓度值</b>
						<div>
							<p>{{status.rqndz}}</p>
						</div>
					</li>
					<!--sp.status.ylz=ylz;
							sp.status.ss=ss;
							sp.status.rqndz=rqndz;-->

					<!--var paramString = "电压: " + abc + ",井盖井盖无破损:" + wps + ",底部:" + db + ",中部:" + zb + ",顶部:" + db;-->

				</ul>
			</section>

			<section class="f_l maxbox edit_list">
				<h3>终端设置</h3>
				<ul>
					<li>
						<b>光敏度</b>
						<!--<p><input class="edit_txt" name="" type="text" placeholder="14.36 klux"></p>-->
						<p>
							<select onchange="gglmd(this[selectedIndex].value)">
								<option value="1">低光敏度</option>
								<option value="2">中光敏度</option>
								<option value="3">高光敏度</option>
							</select>
						</p>
					</li>
					<!--<li>
      <b>设置时间</b>
      <p>
     <input  class="edit_txt"  name="" type="datetime-local" >
      	
      	<input readonly="readonly" class="edit_txt" id="time" v-model="time" name="" type="datetime" >
      </p>
    </li>-->
					<li>
						<b>设置时间</b>
						<p class="radio_single">
							<label class="single"><input v-model="time" type="radio" name="gps" value="1" @click="toggleTime($event)"/>&nbsp;&nbsp;同步手机时间&nbsp;&nbsp;</label>
							<label class="single"><input v-model="time" type="radio" name="gps" value="2" @click="toggleTime($event)" />&nbsp;&nbsp;同步GPS时钟&nbsp;&nbsp;</label>
						</p>

					</li>
					<li>
						<b>开锁/关锁</b>
						<p class="radio_single">
							<input type="radio" v-model="lock" name="lock" value="true" @click="toggleLock($event)" /><label class="single">&nbsp;&nbsp;开锁&nbsp;&nbsp;</lable>&nbsp;&nbsp;
      <input  type="radio" v-model="lock" name="lock" value="false" @click="toggleLock($event)"/>	<label class="single">&nbsp;&nbsp;关锁&nbsp;&nbsp;</lable>
      </p>
    </li>
    
     <li>
     	<b>休眠/唤醒</b>
      <p class="radio_single">
      	<label class="single"><input type="radio" @click="toggleSleep($event)" v-model="awaken" name="awaken" value="true" />&nbsp;&nbsp;休眠&nbsp;&nbsp;</label>&nbsp;&nbsp;
							<label class="single"><input type="radio" @click="toggleSleep($event)" v-model="awaken" name="awaken" value="false" />&nbsp;&nbsp;唤醒&nbsp;&nbsp;</label>
						</p>

					</li>

					<li v-if="domainconfig =='true'">
						<b>设置域名</b>
						<p class="radio_single">
							www.<input type="text" id="domainName" value="tlcs" style="width:50px" />.com
							<a @click="subDomain">确定</a>
						</p>

					</li>

					<li>
						<b>最新固件</b>
						<p>
							<a @click="goUpdate">{{firmware}}</a> ({{updateTime}})</p>
					</li>
				</ul>
			</section>
			<section class="f_l maxbox mar_t mar_f t_c">
				<!--<a class="btn mian_btn" @click="getInfo">获取信息</a>-->
			</section>
			<section class="f_l maxbox mar_t mar_f t_c" v-if="nosubmit =='no'">
				<a class="btn mian_btn" @click="baozhuang">报装</a>
				<p>&nbsp;</p>
			</section>

			<div id="progress_view" style="display: none;">
				<div style="text-align:right; padding:120px 0px;">{{precentText}}</div>
				<div class="hui-progress" id="progress1">
					<span style="width:1%;"></span>
					<div class="hui-progressing"></div>

				</div>

			</div>

		</div>

		<script>
			var bleConnect;

			var sp;

			mui.plusReady(function() {

				sp = new Vue({
					el: "#wrapper",
					data: {
						mac: "",
						version: "",
						updateText: [],
						lastPrecent: 0,
						errCount: 0,
						hexUpdateString: "", //升级文件
						hexUpdateStringLength: 0,
						packageCount: 0, //分包总数
						packageIndex: -1, //正在传送的分包号
						precentText: "",

						status: {
							dy: "",
							jgwps: "",
							db: "",
							zb: "",
							dingbu: "",
							ylz: "",
							ss: "",
							rqndz: ""

						},
						nb: {
							xinhao: "",
							card: ""
						},
						Tid: "",
						lock: "true",
						time: "1",
						awaken: "true",
						gps: "false",
						firmware: "",
						updateTime: "",
						updateUrl: "",
						notifyList: [],
						nosubmit: "",
						domainconfig: "",
						config: {}

					},
					mounted: function() {

						var config = localStorage.getItem("condition");
						if(config == null || config == '') {
							//							loadCondition();
						} else {
							//							this.config= JSON.parse(config);

						}

						var label = this.queryConfig("RSSI");

						console.log("label----" + label);

						var nosubmit = localStorage.getItem("nosubmit");
						this.nosubmit = nosubmit;
						console.log("nosubmit--" + nosubmit);
						//						var zd_id = localStorage.getItem("zd_id");

						var _gself = plus.webview.currentWebview();

						this.Tid = _gself.Tid;
						console.log("从设备列表传来参数 Tid -----" + _gself.Tid);

						var mac = localStorage.getItem("mac");

						this.mac = mac;

						var domainconfig = localStorage.getItem("domainconfig");
						this.domainconfig = domainconfig;

						bleConnect = plus.blecontroler;

						//扫描前初始化蓝牙
						var returnStr = bleConnect.init()
						console.log("returnStr---" + JSON.stringify(returnStr));
						if(returnStr != null) {

							setTimeout(function() {
								getNewSensor();
							}, 260);

							//		

							//					

							//					

						}

					},
					methods: {

						refresh: function() {

							setTimeout(function() {
								//						getNB();
								getNewSensor();
							}, 200);
							//										setTimeout(function() {
							//						getNewSensor();
							//					}, 260);

						},
						queryConfig: function(paramKey) {
							console.log("paramKey----" + paramKey);

							//                      	var datas = sp.config;
							//                      	if(datas!=null&&datas.length>0){
							//                      		for(var i=0;i<datas.length;i++){
							//                      			var cell = datas[i];
							//                      			if(cell.value==paramKey){
							//                      				return cell.label;
							//                      				break;
							//                      			}
							////                      			console.log();
							//                      		}
							//                      	}
						},
						goUpdate: function() {
							//							var tid=this.Tid;
							//							this.mac
							console.log("this.Tid--" + this.Tid);
							console.log("this.mac--" + this.mac);

							hui.open("update.html?time=2018122521", {}, true, {});

						},
						baozhuang: function() {
							//			localStorage.setItem("pid",zdCode);


//								wakeUp();
							var zdId = localStorage.getItem("Tid");
							localStorage.setItem("Tid", this.Tid);

							hui.open("/modules/terminal/expand.html?s=" + apiManage.getNow(), {}, true, {});
						},
						subDomain: function() {
							var param = $("#domainName").val();
							updateDomainName(param);
						},

						getPrecentText: function() {
							var str = "";
							var precent = this.getPrecent();
							if(precent > 0) {
								str = precent + "%[" + this.packageIndex + "/" + this.packageCount + "]";
							}

							self.precentText = str;
							return str;
						},
						getPrecent: function() {
							var precent = 0;
							if(this.packageCount == 0 || this.packageIndex == -1) {} else {
								precent = parseInt(this.packageIndex / this.packageCount * 100);
							}
							return precent;
						},

						begin: function() {
							var _self = this;
							var result = _self.hexUpdateString;
							console.log(" begin result---" + result);
							//						var myFile = document.getElementById("file").files[0];
							if(!result || result == '') {
								hui.toast("请先选择文件!");
								return;
							}
							//						var reader = new FileReader();
							//						//将文件以二进制形式读入页面
							//						reader.readAsBinaryString(myFile);
							//						reader.onload = function(f) {
							//						
							//						}
							//						

							//							var hexString = stringToHex(result, true).replace(/(^\s*)|(\s*$)/g, "");
							_self.hexUpdateString = result;
							_self.hexUpdateStringLength = result.length;

							//console.log(_self.hexUpdateString);
							var len = _self.hexUpdateString.length

							var packageCount = Math.ceil(len / 32);
							_self.packageCount = packageCount;
							_self.packageIndex = 0;

							console.log("文件字节数:" + len + "|分包数:" + packageCount);

							_self.beginUpdate();

							$("#progress_view").show();

						},

						//开始升级
						beginUpdate: function() {
							var _self = this;
							if(!this.Tid || this.Tid.length == 0) {
								hui.toast("请先获取终端编号");
								return;
							}

							if(!this.bleConnect) {
								this.bleConnect = plus.blecontroler;
							}

							var command = "5A3009" + this.Tid + "AA";
							console.log("开始升级" + command);

							hui.loading("升级中..");
							this.bleConnect.writeData(command, function(ret) {
								console.log("返回数据:" + ret);
								if(checkCommand(ret)) {
									hui('#progress1').progressBar(0);
									setTimeout(function() {
										_self.updateing(0);
									}, 3000);
								} else {
									hui.toast("开始升级失败!");
								}
							}, function(err) {
								hui.closeLoading();
								alert(err);
							});
						},

						updateing: function(index) {
							var _self = this;

							if(index > _self.packageCount - 1) {
								setTimeout(function() {
									_self.endUpdate();
								}, 200)

								return;
							}

							var start = index * 32;
							var stop = (index + 1) * 32;
							if(stop > _self.hexUpdateStringLength) {
								stop = _self.hexUpdateStringLength;
							}
							var datastr = _self.hexUpdateString.substring(start, stop);
							if(datastr.length < 32) {
								datastr = getNumberHexFull(datastr);
							}
							datastr = datastr.toUpperCase();

							var command = "A3" + getNumberHex(index)

							var comFull = command + datastr;

							//						console.log("正在升级" + command);
							_self.bleConnect.writeData(comFull, function(ret) {
								console.log("升级返回数据:" + comFull + " " + ret);
								if(checkCommand(ret)) {
									_self.packageIndex = index;
									hui('#progress1').progressBar(_self.getPrecent());

									getTime();
									sp.updateText = sp.updateText.concat(command.toUpperCase() + " | " + datastr);

									_self.errCount = 0;
									setTimeout(function() {
										_self.updateing(index + 1);
									}, 160);

								} else {
									_self.updateError(index, "返回指令:" + ret)
								}
							}, function(err) {
								hui.closeLoading();
								_self.updateError(index, err);
								//alert(err);
							});

						},

						updateError: function(index, msg) {
							var _self = this;
							console.log("升级错误:" + index + "|" + msg);
							if(_self.errCount < 3) {
								_self.errCount++;
								setTimeout(function() {
									_self.updateing(index);
								}, 100);
							} else {
								hui.closeLoading();
								alert("升级失败,请手动结束," + msg)
							};
						},

						endUpdate: function() {
							var _self = this;
							if(!this.Tid || this.Tid.length == 0) {
								hui.toast("请先获取终端编号");
								return;
							}

							if(!this.bleConnect) {
								this.bleConnect = plus.blecontroler;
							}

							var command = "5A3009" + this.Tid + "00";
							console.log("开始升级" + command);
							this.bleConnect.writeData(command, function(ret) {
								console.log("返回数据:" + ret);
								if(checkCommand(ret)) {
									//								hui.toast("升级完成!")
									hui.closeLoading();
									$("#progress_view").hide();
									alert("升级完成!");

									console.log("升级完成!");
								} else {
									hui.toast("开始升级失败!");
									console.log("升级失败!");

								}
							}, function(err) {
								hui.closeLoading();
								hui.toast(err);
								console.log(err);
							});
						},

						showStatus: function(param) {
							if(param == '00') {
								return "";
							} else {

							}
						},
						getInfo: function() {
							getNB();
							//					getStatus();
						},
						show: function(value) {
							hui.toast(value);
						},

						toggleLock: function(e) {
							var value = $(e.currentTarget).val();
							if(value == 'false') {
								lock();
							} else {
								unlock();
							}
						},

						toggleTime: function(e) {
							var value = $(e.currentTarget).val(); //是你绑定事件的元素
							console.log(value);
							if(value == '1') {
								updateTime()
							} else {
								updateGPS();
							}
						},

						toggleSleep: function(e) {
							var value = $(e.currentTarget).val(); //是你绑定事件的元素
							console.log(value);
							if(value == 'true') {
								sleep();
							} else {
								wakeUp();
							}
						},
						update: function(param) {
							hui.confirm("确定要更新固件到版本" + param + " 么？", ['取消', '确定'], function() {
								console.log('确认...');
								download("");
							}, function() {
								console.log('取消...');
							});

						},
						back: function() {
							localStorage.setItem("zd_id", "");
							localStorage.setItem("mac", "");

							localStorage.setItem("nosubmit", "");
							hui.back();
						}
					}

				});

				settingDateControl("time");

				function settingDateControl(pid) {

					var selectDateDom = $('#' + pid);
					var showDateDom = $('#showDate');
					// 初始化时间
					var now = new Date();
					var nowYear = now.getFullYear();
					var nowMonth = now.getMonth() + 1;
					var nowDate = now.getDate();
					selectDateDom.attr('data-year', nowYear);
					selectDateDom.attr('data-month', nowMonth);
					selectDateDom.attr('data-date', nowDate);
					// 数据初始化
					function formatYear(nowYear) {
						var arr = [];
						for(var i = nowYear - 5; i <= nowYear + 5; i++) {
							arr.push({
								id: i + '',
								value: i + '年'
							});
						}
						return arr;
					}

					function formatMonth() {
						var arr = [];
						for(var i = 1; i <= 12; i++) {

							arr.push({
								id: i + '',
								value: i + '月'
							});
						}
						return arr;
					}

					function formatDate(count) {
						var arr = [];
						for(var i = 1; i <= count; i++) {

							arr.push({
								id: i + '',
								value: i + '日'
							});
						}
						return arr;
					}
					var yearData = function(callback) {

						callback(formatYear(nowYear))
					}
					var monthData = function(year, callback) {
						callback(formatMonth());
					};
					var dateData = function(year, month, callback) {
						if(/^(1|3|5|7|8|10|12)$/.test(month)) {
							callback(formatDate(31));
						} else if(/^(4|6|9|11)$/.test(month)) {
							callback(formatDate(30));
						} else if(/^2$/.test(month)) {
							if(year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
								callback(formatDate(29));
							} else {
								callback(formatDate(28));
							}
						} else {
							throw new Error('month is illegal');
						}
					};
					var hourData = function(one, two, three, callback) {
						var hours = [];
						for(var i = 0, len = 24; i < len; i++) {
							if(i < 10) {
								i = "0" + i;
							}
							hours.push({
								id: i,
								value: i + '时'
							});
						}
						callback(hours);
					};
					var minuteData = function(one, two, three, four, callback) {
						var minutes = [];
						for(var i = 0, len = 60; i < len; i++) {
							if(i < 10) {
								i = "0" + i;
							}
							minutes.push({
								id: i,
								value: i + '分'
							});
						}
						callback(minutes);
					};

					var secondsData = function(one, two, three, four, five, callback) {
						var seconds = [];
						for(var i = 0, len = 60; i < len; i++) {
							if(i < 10) {
								i = "0" + i;
							}
							seconds.push({
								id: i,
								value: i + '秒'
							});
						}
						callback(seconds);
					};
					selectDateDom.bind('click', function() {
						var oneLevelId = selectDateDom.attr('data-year');
						var twoLevelId = selectDateDom.attr('data-month');
						var threeLevelId = selectDateDom.attr('data-date');
						var fourLevelId = selectDateDom.attr('data-hour');
						var fiveLevelId = selectDateDom.attr('data-minute');
						var sixLevelId = showDateDom.attr('data-second');

						var iosSelect = new IosSelect(6, [yearData, monthData, dateData, hourData, minuteData, secondsData], {
							title: '选择时间',
							itemHeight: 35,
							itemShowCount: 9,
							oneLevelId: oneLevelId,
							twoLevelId: twoLevelId,
							threeLevelId: threeLevelId,
							fourLevelId: fourLevelId,
							fiveLevelId: fiveLevelId,
							sixLevelId: sixLevelId,

							callback: function(selectOneObj, selectTwoObj, selectThreeObj, selectFourObj, selectFiveObj, selectSixObj) {
								selectDateDom.attr('data-year', selectOneObj.id);
								selectDateDom.attr('data-month', selectTwoObj.id);
								selectDateDom.attr('data-date', selectThreeObj.id);
								selectDateDom.attr('data-hour', selectFourObj.id);
								selectDateDom.attr('data-minute', selectFiveObj.id);
								showDateDom.attr('data-second', selectSixObj.id);

								//                  showDateDom.html(selectOneObj.value + ' ' + selectTwoObj.value + ' ' + selectThreeObj.value + ' ' + selectFourObj.value + ' ' + selectFiveObj.value);
								var params = selectOneObj.value + '' + selectTwoObj.value + '' + selectThreeObj.value + '' + selectFourObj.value + '' + selectFiveObj.value + selectSixObj.value;
								console.log(params);
								params = params.replace("年", "-");
								params = params.replace("月", "-");
								params = params.replace("日", " ");
								params = params.replace("时", ":");
								params = params.replace("分", ":");
								params = params.replace("秒", "");

								sp[pid] = params;
							}
						});
					});

				}

							loadDetail();
				//查询固件版本
				function loadDetail() {
					var path = urlManager.getFirmware();
					console.log(path);
					var username = localStorage.getItem("username");
					var sec = localStorage.getItem("sec_pwd");
					var time = apiManage.getNow();
					var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
					//				console.log(key);
					var paramKey = hex_md5(key);

					var readyParam = {
						cusId: apiManage.getCompanyId(),
						status: "0"
					};
					$.ajax({
						type: "POST",
						data: readyParam,
						url: path + "&time=" + time,
						beforeSend: function(request) {
							request.setRequestHeader("loginName", username);
							request.setRequestHeader("time", time);
							request.setRequestHeader("sign", paramKey);
							//		            request.setRequestHeader("Content-Type","application/text");

						},
						success: function(result) {
							console.log("版本库文件接口============================" + JSON.stringify(result));
							//						sp.zdlist = result.list;
							sp.firmware = result.version;
							sp.updateTime = result.createDateStr.substring(0, 10);
							sp.updateUrl = result.url;

						}
					});

				}

				function getFileFromWeb() {
					plus.io.resolveLocalFileSystemURL(
						"file:" + sp.updateUrl,
						function(entry) {
							alert(entry.fullPath);
							//此处相关知识请见 DirectoryEntry 文件系统中的目录对象，用于管理特定的本地目录
						},
						function(e) {
							alert("Resolve file URL failed: " + e.message);
						}
					);
				}

				function isString(str) {
					return(typeof str == 'string') && str.constructor == String;
				}

				//  		var url = "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1308878769,636194597&fm=26&gp=0.jpg";
				var tmp_url = "http://124.232.165.110:35680/cssk/uploadFiles/filesVersion/20181130/1543560818277.jpg";

				function download(url) { //下载文件

					url = sp.updateUrl;

					var dtask = plus.downloader.createDownload(url, {}, function(d, status) {
						// 下载完成
						if(status == 200) {

							var size = d.downloadedSize; //
							console.log("文件---" + JSON.stringify(d));
							size = (size / 1024).toFixed(1);
							hui.toast("升级固件下载完成 " + "文件大小: " + size + " kb");
							var fileUrl = d.filename;

							plus.io.resolveLocalFileSystemURL(fileUrl, function(entry) {

								//				        console.log("entry"+ JSON.stringify(entry));

								console.log("entry is file--" + entry.isFile);

								var reader = null;
								entry.file(function(file) {
									console.log("File size: " + file.size);

									console.log("file -" + JSON.stringify(file));

									reader = new plus.io.FileReader();

									reader.onloadend = function(e) {
										console.log("Read success -" + JSON.stringify(e.target));
										var params = e.target.result;
										//					    			readHexParam(params);
										params = params.replace("data:application/octet-stream;base64,", "");
										params = base64toHEX(params);
										sp.hexUpdateString = params; //升级文件
										sp.hexUpdateStringLength = params.length;
										sp.begin();

									};

									reader.onerror = function(e) {
										console.log("Read error--- " + e);
									};

									reader.readAsDataURL(file);

								}, function(e) {
									alert(e.message);
								});

								reader.abort();

							});

						} else {
							alert("Download failed: " + status);
						}
					});
					dtask.start();
				}

			});

			function base64toHEX(base64) {

				var raw = window.atob(base64);

				var HEX = '';

				for(i = 0; i < raw.length; i++) {

					var _hex = raw.charCodeAt(i).toString(16)

					HEX += (_hex.length == 2 ? _hex : '0' + _hex);

				}
				return HEX.toUpperCase();

			}

			function readHexParam(params) {
				//				var tmp= params;
				params = params.replace(/:/g, "");
				params = params.replace(/\r\n/g, "");
				//				console.log("params==="+params);

				console.log("处理后params===  " + params);
				sp.hexUpdateString = params; //升级文件
				sp.hexUpdateStringLength = params.length;
				sp.begin();

				return params;
				//				var hexArray = params.split(":");
				//				   for(var i=0;i<hexArray.length;i++){
				//				   	    console.log("line:"+ i+"  -  " +hexArray[i]);
				//				   }

			}

			function hexStringToByte(str) {
				var cutLength = 16;
				if(!str) {
					return new Uint8Array();
				}

				var a = [];
				for(var i = 0, len = str.length; i < len; i += cutLength) {
					var param = parseInt(str.substr(i, cutLength), 16);
					a.push(param);
					console.log(param);
				}

				return new Uint8Array(a);
			}

			//=========================================设置终端相关方法

			//更新固件
			function updateFirmware() {

			}

			//唤醒终端
			function wakeUp() {
				if(!sp.Tid || sp.Tid.length == 0) {
					hui.toast("请先获取终端编号");
					return;
				}

				var command = "5A1109" + sp.Tid + "01";
				console.log("唤醒命令" + command);
				bleConnect.writeData(command, function(ret) {
					console.log("返回数据:" + ret);
					sp.notifyList = sp.notifyList.concat("唤醒成功: " + ret);
					hui.toast("唤醒成功");
				}, function(err) {
					hui.closeLoading();
					alert(err);
				});
			}

			//休眠终端
			function sleep() {
				if(!sp.Tid || sp.Tid.length == 0) {
					hui.toast("请先获取终端编号");
					return;
				}
				var command = "5A1109" + sp.Tid + "02";
				console.log("休眠命令" + command);
				bleConnect.writeData(command, function(ret) {
					console.log("休眠成功返回数据:" + ret);
					sp.notifyList = sp.notifyList.concat("休眠成功: " + ret);
					hui.toast("休眠成功 ");
				}, function(err) {
					hui.closeLoading();
					alert(err);
				});
			}

			//关锁
			function lock() {
				if(!sp.Tid || sp.Tid.length == 0) {
					hui.toast("请先获取终端编号");
					return;
				}
				//					5a 12 09 01 01 01 01 01 00 00 01 01 40

				var command = "5A1209" + sp.Tid + "02";
				console.log("关锁命令" + command);
				bleConnect.writeData(command, function(ret) {
					console.log("关锁返回数据:" + ret);
					sp.notifyList = sp.notifyList.concat("关锁成功: " + ret);

					hui.toast("关锁成功 ");
				}, function(err) {
					hui.closeLoading();
					alert(err);
				});
			}

			//开锁
			function unlock() {
				if(!sp.Tid || sp.Tid.length == 0) {
					hui.toast("请先获取终端编号");
					return;
				}
				//					5a 12 09 01 01 01 01 01 00 00 01 01 40

				var command = "5A1209" + sp.Tid + "01";
				console.log("开锁命令" + command);
				bleConnect.writeData(command, function(ret) {
					console.log("开锁返回数据:" + ret);
					sp.notifyList = sp.notifyList.concat("开锁成功: " + ret);

					hui.toast("开锁成功");

				}, function(err) {
					hui.closeLoading();
					alert(err);
				});
			}

			//终端光感灵敏度
			function gglmd(type) {
				if(!sp.Tid || sp.Tid.length == 0) {
					hui.toast("请先获取终端编号");
					return;
				}
				//					5a 13 09 01 01 01 01 01 00 00 01 03 43

				var setting_value = "";
				if(type == '1') {
					setting_value = "01";
				} else if(type == '2') {
					setting_value = "02";
				} else if(type == '3') {
					setting_value = "03";
				} else {

				}
				var command = "5A1309" + sp.Tid + setting_value;
				console.log("光感灵敏度设置" + command);
				bleConnect.writeData(command, function(ret) {
					if(ret.indexOf("state") != -1) {
						return;
					}

					console.log("返回数据:" + ret);
					sp.notifyList = sp.notifyList.concat("光感灵敏度设置成功: " + ret);
					hui.toast("光感灵敏度设置成功");
					console.log("光感灵敏度设置成功: " + ret);

				}, function(err) {
					hui.closeLoading();
					alert(err);
				});
			}

			//设置同步GPS时钟
			function updateGPS() {
				//				5a 14 10 01 01 01 01 01 00 00 01 01 00 00 00 00 00 00 00 5f
				var param = "5a1410010101010100000101000000000000005f";

				var command = "5a1410" + sp.Tid + "0100000000000000";
				console.log("设置同步GPS时钟" + command);
				bleConnect.writeData(command, function(ret) {
					console.log("返回数据:" + ret);
					sp.notifyList = sp.notifyList.concat("同步GPS时钟设置成功: " + ret);
					hui.toast("同步GPS时钟成功");
				}, function(err) {
					hui.closeLoading();
					hui.toast(err);
					//					alert(err);
				});
			}

			//			updateTime();
			//同步手机时间设置
			function updateTime() {
				//				

				var time = apiManage.getNowYYMMDDHHMMSS();
				console.log("time-----" + time);
				var timeArray = time.split("-");
				var year = timeArray[0];
				var month = timeArray[1];
				var date2 = timeArray[2];
				var hour = timeArray[3];
				var min = timeArray[4];
				var sec = timeArray[5];

				var timeParam = year + month + date2 + hour + min + sec;
				console.log("timeParam-----" + timeParam);

				year = toHex(year);
				if(year.length < 4) {
					year = "0" + year;
				}

				month = toHex(month);
				if(month.length < 2) {
					month = "0" + month;
				}
				date2 = toHex(date2);
				if(date2.length < 2) {
					date2 = "0" + date2;
				}
				hour = toHex(hour);
				if(hour.length < 2) {
					hour = "0" + hour;
				}
				min = toHex(min);
				if(min.length < 2) {
					min = "0" + min;
				}
				sec = toHex(sec);
				if(sec.length < 2) {
					sec = "0" + sec;
				}
				timeParam = year + month + date2 + hour + min + sec;

				console.log("hex timeParam-----" + timeParam);

				var command = "5a1410" + sp.Tid + "00" + timeParam;
				console.log("设置同步手机时间" + command);
				bleConnect.writeData(command, function(ret) {
					if(ret.indexOf("state") != -1) {
						return;
					}

					console.log("返回数据:" + ret);
					sp.notifyList = sp.notifyList.concat("同步手机时间设置成功: " + ret);
					hui.toast("同步手机时间成功");
				}, function(err) {
					hui.closeLoading();
					console.log(err);
					//					alert(err);
				});
			}

			//获取NB信息
			function getNB() {
				$("#nbBtn").hide();
				var command = "5a1508" + sp.Tid;
				console.log("获取NB信息 " + command);
               hui.loading("");
				bleConnect.writeData(command, function(ret) {
//					console.log("返回数据:" + ret);
					hui.closeLoading();
					sp.notifyList = sp.notifyList.concat("获取NB信息成功: " + ret);

					console.log(ret);
					var all = ret;
					var xinhao = all.substr(14, 2);
					var number2 = all.substr(16, 20);

					//					parseInt(sixteen,16);
					console.log("信号: " + parseInt(xinhao, 16) + ",  卡号:" + number2);
					//					hui.toast("信号: "+parseInt(xinhao,16)+",  卡号:"+number2);
					sp.nb.xinhao = parseInt(xinhao, 16);
					sp.nb.card = number2;
					console.log("sp.nb---" + JSON.stringify(sp.nb));

					setTimeout(function() {
						getVersion();
					}, 260);

				}, function(err) {
					hui.closeLoading();
					console.log(err);
					//					alert(err);
				});
			}

			//获取固件版本号
			function getVersion() {
				$("#nbBtn").hide();
				var command = "5a4008" + sp.Tid;
				console.log("获取固件版本号 " + command);

				bleConnect.writeData(command, function(ret) {
//					console.log("返回数据 固件版本号:" + ret);
					sp.notifyList = sp.notifyList.concat("获取固件版本号成功: " + ret);

					console.log(ret);
					var all = ret;
					var versionStr1 = all.substr(22, 2);
					var versionStr2 = all.substr(24, 2);

					var version = versionStr1 + "." + versionStr2;
					console.log("version--" + version);
					sp.version = version;

				}, function(err) {
					hui.closeLoading();
					console.log(err);
					//					alert(err);
				});
			}

			//获取最新传感数据 2019-1-10  接口文档 2.2.3
			function getNewSensor() {

				var command = "5a1608" + sp.Tid;
				console.log("获取最新传感数据 " + command);
               hui.loading("");
				bleConnect.writeData(command, function(ret) {
					console.log("返回 最新传感数据:" + ret);
					hui.closeLoading();
					//					hui.toast(ret);

					setTimeout(function() {
						getNB();
					}, 200);

					var paramString = ret;

					var dianya = paramString.substr(6, 4);
					console.log('电压值---' + parseInt(dianya, 16) / 1000);
					dianya = parseInt(dianya, 16) / 1000;

					var wps = paramString.substr(10, 2);

					wps = parseInt(wps, 16);
					if(wps == 0) {
						wps = "未破损";
					} else {
						wps = "破损";

					}

					var dib = paramString.substr(12, 2);
					dib = parseInt(dib, 16);

					dib = (dib == 0) ? "关闭" : "开启";

					var zb = paramString.substr(14, 2);
					zb = parseInt(zb, 16);

					zb = (zb == 0) ? "关闭" : "开启";

					var dingb = paramString.substr(16, 2);
					dingb = parseInt(dingb, 16);
					dingb = (dingb == 0) ? "关闭" : "开启";

					var rqndz = paramString.substr(18, 4);
					rqndz = parseInt(rqndz, 16) / 100 + " %";

					var ylz = paramString.substr(22, 4);
					ylz = parseInt(ylz, 16) + " KPa";
					var ss = paramString.substr(26, 4);

					ss = parseInt(ss, 16) / 100 + "米";

					console.log("井盖未破损:" + wps + " 井盖底部开启：" + dib + "  井盖中部未开启: " + zb + " 井盖顶部未开启" + dingb + " 燃气浓度值:" + rqndz + " 压力值: " + ylz + " , 水深:" + ss);

					sp.status.dy = dianya;
					sp.status.jgwps = wps;
					sp.status.db = dib;
					sp.status.zb = zb;
					sp.status.dingbu = dingb;

					sp.status.ylz = ylz;
					sp.status.ss = ss;
					sp.status.rqndz = rqndz;

					//					sp.notifyList = sp.notifyList.concat("获取固件版本号成功: " + ret);

				}, function(err) {
					hui.closeLoading();
					console.log(err);
					//					alert(err);
				});
			}

			//获取井盖终端状态
			function getStatus() {

				var command = "5a1608" + sp.Tid;
				console.log("获取井盖终端状态 " + command);
				bleConnect.writeData(command, function(ret) {
					if(ret.indexOf("state") != -1) {
						return;
					}

					setTimeout(function() {
						getVersion();
					}, 260);

					console.log("返回数据:" + ret);
					sp.notifyList = sp.notifyList.concat("获取井盖终端状态成功: " + ret);

					console.log("获取井盖终端状态成功: " + ret);

					var status = ret.substr(2, 2);
					if(status == '22') {
						//							hui.toast("获取成功 ");
					} else {
						//						hui.toast("获取失败");

					}
					console.log("dianya:---" + ret.substr(22, 4));
					var dianya1 = ret.substr(22, 4);
					//					var dianya2 = ret.substr(26,2);

					//					井盖无破损，底部开启，中部未开启，顶部未开启
					var wps = ret.substr(26, 2);
					var db = ret.substr(28, 2);
					var zb = ret.substr(30, 2);
					var dingbu = ret.substr(32, 2);
					var abc = Math.round(parseFloat(parseInt(dianya1, 16))) / 1000;

					wps = (wps == "00") ? "无破损" : "有破损";
					db = (db == "00") ? "未开启" : "开启";
					zb = (zb == "00") ? "未开启" : "开启";
					dingbu = (dingbu == "00") ? "未开启" : "开启";

					var paramString = "电压: " + abc + ",井盖无破损:" + wps + ",底部:" + db + ",中部:" + zb + ",顶部:" + db;
					console.log(paramString);

					// { dy:"",jgwps:"",db:"",zb:"",db:""}
					sp.status.dy = abc;
					sp.status.jgwps = wps;
					sp.status.db = db;
					sp.status.zb = zb;
					sp.status.dingbu = dingbu;
					//					sp.status = paramString;

				}, function(err) {
					hui.closeLoading();
					console.log(err);
					//					alert(err);
				});
			}

			$("#subDomain").click(function() {
				alert('2');
				var param = $("#domainName").val();
				updateDomainName(param);
			});

			//设置域名
			function updateDomainName(param) {
				var domain = stringToHex(param, true);
				var plus = domain.length;
				//				domain+="00000000";
				var num = 8 - plus / 2;
				for(var i = 0; i < num; i++) {
					domain += "00";
				}
				console.log("domain.length -" + domain.length)
				//				if(plus>0) {
				//					domain = domain + "00";
				//				}
				var command = "5a1810" + sp.Tid + domain;
				console.log("域名   " + domain);

				console.log("井盖终端外网服务器域名设置 " + command);
				bleConnect.writeData(command, function(ret) {
					console.log("返回数据:" + ret);
					sp.notifyList = sp.notifyList.concat("井盖终端外网服务器域名设置: " + ret);

					console.log("域名设置返回: " + ret);
					hui.toast("域名设置成功: ");

				}, function(err) {
					hui.closeLoading();
					hui.toast(err);
					//					alert(err);
				});
			}

			function toHex(param) {
				var tmp = parseInt(param);
				var tmp2 = tmp.toString(16);

				//				console.log(tmp2);
				return tmp2;
			}

			//检查是否
			function checkCommand(command) {
				return command.toUpperCase().indexOf('5A2308') >= 0;
			}

			function stringToHex(str, zero) {　　　　
				var val = "";　　　　
				for(var i = 0; i < str.length; i++) {　　
					var value = zero ? addPreZero(str.charCodeAt(i).toString(16)) : str.charCodeAt(i).toString(16);　　　　
					//if(i%2 == "")　　　　　　　　
					//  val += " " + value;　　　　　　
					//else　　　　　　　　 
					val += value;　　　　
				}　　　　
				return val;　　
			}

			function addPreZero(num) {
				return('00' + num).slice(-2);
			}

			function getNumberHex(num) {
				var hex = '0000' + num.toString(16);
				return hex.substring(hex.length - 4, hex.length);
			}

			var startTime;

			function getTime() {

				var t = new Date().getTime();
				if(!startTime) {
					startTime = t;
				}
				var usedTime = t - startTime

				var date3 = getTimeDiff(startTime, t);
				var timeNeed = usedTime * 100;
				timeNeed = parseInt(timeNeed / sp.getPrecent()) - usedTime;
				//console.log("需要时间" + timeNeed);

				var str = "已用时:" + date3 + ",预计还需要" + getDiff(timeNeed);
				//				hui("#time_count").html(str);
				//				console.log(str);

			}

			function getTimeDiff(start, end) {
				if(start == end) {
					return "0秒";
				}

				return getDiff(end - start);
			}

			function getDiff(date3) {
				//计算出相差天数
				var days = Math.floor(date3 / (24 * 3600 * 1000))

				//计算出小时数
				var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
				var hours = Math.floor(leave1 / (3600 * 1000))
				//计算相差分钟数
				var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
				var minutes = Math.floor(leave2 / (60 * 1000))
				//计算相差秒数
				var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
				var seconds = Math.round(leave3 / 1000)
				var str = days > 0 ? (days + "天 ") : "";
				str += hours > 0 ? (hours + "小时 ") : "";
				str += minutes > 0 ? (minutes + " 分钟") : "";
				str += seconds > 0 ? (seconds + " 秒") : "";
				return str;
			}

			function getNumberHexFull(str) {
				var hex = '00000000000000000000000000000000' + str;
				return hex.substring(hex.length - 32, hex.length);
			}

			//获取传感配置
			function loadCondition() {

				var username = localStorage.getItem("username");
				var sec = localStorage.getItem("sec_pwd");
				var time = apiManage.getNow();
				var key = "loginName=" + username + "&passWord=" + sec + "&time=" + time;
				var paramKey = hex_md5(key);
				var jsonParam = JSON.stringify({
					loginName: username,
					time: time,
					key: paramKey
				});

				console.log("jsonParam:  " + jsonParam);

				var path = urlManager.getAlarmruleCondition();
				//var path = urlManager.terminalDetail()+"?terminalCode=0143010201000003"

				console.log("path:  " + path);
				$.ajax({
					type: "GET",
					url: path,
					beforeSend: function(request) {
						request.setRequestHeader("loginName", username);
						request.setRequestHeader("time", time);
						request.setRequestHeader("sign", paramKey);
						request.setRequestHeader("Content-Type", "application/text");

					},
					success: function(result) {
						//						hui.closeLoading();
						console.log("再次获取配置详情:" + JSON.stringify(result));
						sp.config = result;
						//					   localStorage.setItem("condition",JSON.stringify(result));//配置信息保存到缓存 便于存储

					}

				});

			}
		</script>

	</body>

</html>